package com.ruoyi.order.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.*;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.ruoyi.cart.remote.IPmsCartRemoteService;
import com.ruoyi.common.core.constant.Constants;
import com.ruoyi.common.core.domain.Result;
import com.ruoyi.order.config.PayConfig;
import com.ruoyi.order.service.IPayService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.*;

/**
 * @author lemon
 * @date 2024/12/30 21:04
 **/
@Service
public class PayServiceImpl implements IPayService {

    @Autowired
    private AlipayConfig alipayConfig;
    @Autowired
    private PayConfig payConfig;

    @Autowired
    private IPmsCartRemoteService remoteService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    // 创建线程池
    private ThreadPoolExecutor orderExecutor;

    @PostConstruct
    public void init() {
        orderExecutor = new ThreadPoolExecutor(
            10, // 核心线程数
            20, // 最大线程数
            60L, // 空闲线程存活时间
            TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(1000), // 工作队列
            new ThreadFactory() {
                private int counter = 1;
                @Override
                public Thread newThread(Runnable r) {
                    Thread thread = new Thread(r);
                    thread.setName("order-thread-" + counter++);
                    return thread;
                }
            },
            new ThreadPoolExecutor.CallerRunsPolicy() // 拒绝策略
        );
    }

    @Override
    public String generatePay(String totalPrice, Long[] skuIds) throws AlipayApiException {
        // 生成订单号
        String orderNo = RandomUtil.randomNumbers(16);

        // 1. 异步处理订单创建
        CompletableFuture<Void> createOrderFuture = CompletableFuture.runAsync(() -> {
            // 发送订单创建消息到MQ
            Map<String, Object> orderMessage = new HashMap<>();
            orderMessage.put("orderNo", orderNo);
            orderMessage.put("skuIds", skuIds);
            orderMessage.put("totalPrice", totalPrice);

            rabbitTemplate.convertAndSend("order.exchange", "order.create", orderMessage);
        }, orderExecutor);

        // 2. 异步清理购物车
        CompletableFuture<Void> clearCartFuture = CompletableFuture.runAsync(() -> {
            Result result = remoteService.removePayed(skuIds);
            if (result.getCode() == Constants.ERROR) {
                throw new RuntimeException("清理购物车失败: " + result.getMsg());
            }
        }, orderExecutor);

        // 3. 异步生成支付参数
        CompletableFuture<AlipayTradePagePayRequest> payRequestFuture = CompletableFuture.supplyAsync(() -> {
            AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
            AlipayTradePagePayModel model = new AlipayTradePagePayModel();

            model.setOutTradeNo(orderNo);
            model.setTotalAmount(totalPrice);
            model.setSubject("cart_pay");
            model.setProductCode("FAST_INSTANT_TRADE_PAY");
            model.setQrPayMode("1");
            model.setQrcodeWidth(200L);

            // 设置订单超时时间
            Calendar instance = Calendar.getInstance();
            instance.add(Calendar.MINUTE, 30);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            model.setTimeExpire(sdf.format(instance.getTime()));

            request.setBizModel(model);
            request.setReturnUrl(payConfig.getReturnUrl());
            request.setNotifyUrl(payConfig.getNotifyUrl());

            return request;
        }, orderExecutor);

        try {
            // 等待所有异步任务完成
            CompletableFuture.allOf(createOrderFuture, clearCartFuture, payRequestFuture).join();

            // 获取支付请求参数并调用支付宝接口
            AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig);
            AlipayTradePagePayRequest request = payRequestFuture.get();
            AlipayTradePagePayResponse response = alipayClient.pageExecute(request, "POST");

            if (!response.isSuccess()) {
                // 发送订单取消消息
                rabbitTemplate.convertAndSend("order.exchange", "order.cancel", orderNo);
                throw new RuntimeException("调用支付宝接口失败: " + response.getMsg());
            }

            return response.getBody();

        } catch (Exception e) {
            // 发送订单取消消息
            rabbitTemplate.convertAndSend("order.exchange", "order.cancel", orderNo);
            throw new RuntimeException("创建支付订单失败", e);
        }
    }

    @PreDestroy
    public void destroy() {
        if (orderExecutor != null) {
            orderExecutor.shutdown();
            try {
                if (!orderExecutor.awaitTermination(30, TimeUnit.SECONDS)) {
                    orderExecutor.shutdownNow();
                }
            } catch (InterruptedException e) {
                orderExecutor.shutdownNow();
                Thread.currentThread().interrupt();
            }
        }
    }
}
